<?php
class Sms{
	const APIURL = "http://weirenwu.weibo.com/api/index.php";		//微博主接口地址
	const MERCHID = 1001;		//商户ID
	const SKEY = "35ca35aex45e59b4foo70161a38c59u";			//密钥
	const VERSION = 'v1.0';		//版本，目前固定为v1.0
	/**
	 * 发送短信
	 * @param type $phones	电话号码，多个号码用半角逗号隔开，最多20个
	 * @param type $text	文本
	 * @param type $timestamp
	 * @param type $ip
	 * @return json 返回错误时返回{error_code,error}
	 *					正确时返回{"data":[{"phone":"13488657095","res":"18400329"}]},如果多个号码有成功，又失败，返回依然是正确的，需要自行判断各个号码是否成功
	 */
	public function send($phones,$text,$timestamp,$ip='')
	{
		$param = array('bid'=>self::MERCHID,
						'version'=>self::VERSION,
						'phones'=>$phones,
						'text'=>$text,
						'timestamp'=>$timestamp,
						'ip'=>$ip);
		$wrw = new weirenwuApi(self::APIURL."/sms/send", self::MERCHID, self::SKEY,self::VERSION);
		$param['sign'] = $wrw->sign($param);	//生成签名
		//print_r($param);
		$res = $wrw->post($param);
		//var_dump(json_decode($res));
		return $res;
	}
}
class weirenwuApi{
	protected $apiUrl = "";
	protected $merchid = 1;
	protected $skey = "";
	protected $version = 'v1.0';
	function __construct($url,$merchid,$skey,$version) {
		$this->apiUrl = $url;
		$this->merchid = $merchid;
		$this->skey = $skey;
		$this->version = $version;
	}
	/**
	 * 
	 * @param type $param
	 * @return type
	 */
	function post($param){
		$strParam = $this->paramArrtostr($param);
		$ci = curl_init();
		curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
		curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ci, CURLOPT_HEADER, FALSE);
		curl_setopt($ci, CURLOPT_POST, TRUE);
		curl_setopt($ci, CURLOPT_POSTFIELDS, $strParam);
		curl_setopt($ci, CURLOPT_URL, $this->apiUrl );
//		curl_setopt($ci, CURLINFO_HEADER_OUT, TRUE );
//		curl_setopt($ci, CURLOPT_USERPWD, "weirenwu@joyinter.com:weirenwu.123456");
		$ret = curl_exec($ci);
		curl_close ($ci);
		return $ret;
	}
	function paramArrtostr($param){
		$arr = array();
		foreach($param as $key=>$val){
			$arr [] = $key."=".$val;
		}
		return implode("&", $arr);
	}
	function sign($param){
		$strParam = $this->paramArrtostr($param) . "&key=".$this->skey;
		$mySign = md5($strParam);
		return $mySign;
	}
}
